package com.sdx.console.system.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.console.service.OrgConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.finOrderChannel.entity.FinOrderChannel;
import com.sdx.console.finOrderChannel.service.FinOrderChannelService;
import com.sdx.console.live.entity.CourseLive;
import com.sdx.console.system.entity.ChannelSet;
import com.sdx.console.system.service.ChannelSetService;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 渠道 接口
 */
@RequestMapping("/system/channelSet")
@Controller
public class ChannelSetController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(ChannelSetController.class);
    private static final String MODEL = "/system/channelSet";


    @Resource
	private ChannelSetService channelSetService;

	@Resource
	private OrgConsoleService orgConsoleService;

	@Resource
	private CorePlatformService platformService;

    @Resource
    private FinOrderChannelService finOrderChannelService;

    /* 页面 */

	/**
	 * 初始化页面需要的列表数据，
	 * @param view 业务模块，来源渠道
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		Integer accessType = platformService.getAccessType(request);
		view.addObject("accessType",accessType);
		view.addObject("orgList",orgConsoleService.getOrgs());
	}

    @GetMapping("/index.do")
    @Function("system.channelSet.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
        setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("system.channelSet.edit")
    @ResponseBody
    public ModelAndView edit(String channelCode,HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        setPageParam(view,request);
        CoreUser user = getLoginUser(request);
        ChannelSet set = new ChannelSet();
        set.setChannelCode(channelCode);
        set.setTenantId(user.getTenantId());
        ChannelSet channelSet = channelSetService.getSqlManager().templateOne(set);  //queryById(channelCode);
        view.addObject("channelSet", channelSet);
        if (StringUtils.isNotEmpty(channelSet.getChannelJson())) {
	        JSONObject jsonObject = JSON.parseObject(channelSet.getChannelJson());
	        view.addObject("jsonInfo",jsonObject);
        }
		try {
			view.addObject("channelSetJson", JacksonUtils.toJsonString(channelSet,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("system.channelSet.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("system.channelSet.query")
    @ResponseBody
    public JsonResult<PageQuery> list(ChannelSet condtion,HttpServletRequest request)
    {
        CoreUser user = getLoginUser(request);
        condtion.setTenantId(user.getTenantId());
	    Integer accessType = platformService.getAccessType(request);
	    if (accessType.intValue()==3) {
		    condtion.setOrgId(user.getOrgId().intValue());
	    }
	    PageQuery page = condtion.getPageQuery();
        channelSetService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,ChannelSet channelSet,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);
        Integer accessType = platformService.getAccessType(request);
		if (channelSet.getJsonInfo()!=null) {
			channelSet.setChannelJson(JSON.toJSONString(channelSet.getJsonInfo()));
		}
        channelSet.setTenantId(user.getTenantId());
    	if (isNew) {
            if(accessType==null || accessType!=6){
                channelSet.setOrgId(user.getOrgId().intValue());
            }
			channelSet.setCreatedBy(user.getId().intValue());
			channelSet.setCreatedName(user.getName());
			channelSet.setCreatedTime(new Date());
            boolean save = channelSetService.save(channelSet);
            if(save){
                initOrderChannel(user, channelSet.getChannelCode());
            }
		} else {
			channelSet.setUpdatedBy(user.getId().intValue());
			channelSet.setUpdatedName(user.getName());
			channelSet.setUpdatedTime(new Date());
			channelSetService.updateTemplate(channelSet);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("system.channelSet.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ChannelSet channelSet,HttpServletRequest request
		)
    {
	    Integer accessType = platformService.getAccessType(request);

	    if (accessType.intValue()==3) {
		    CoreUser user = getLoginUser(request);
	    	channelSet.setOrgId(user.getOrgId().intValue());
	    }
        return save(true,channelSet,request
		);
    }

    @PostMapping("/update.json")
    @Function("system.channelSet.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ChannelSet channelSet,HttpServletRequest request
		) {
		return save(false,channelSet,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("system.channelSet.query")
    @ResponseBody
    public JsonResult<ChannelSet>queryInfo(String channelCode,HttpServletRequest request) {
        CoreUser user = getLoginUser(request);
        ChannelSet set = new ChannelSet();
        set.setChannelCode(channelCode);
        set.setTenantId(user.getTenantId());
        ChannelSet channelSet = channelSetService.getSqlManager().templateOne(set);//               queryById( channelCode);
        return  JsonResult.success(channelSet);
    }

    @PostMapping("/delete.json")
    @Function("system.channelSet.del")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        //List<Long> idList = ConvertUtil.str2longs(ids);
		List<String> idList = new ArrayList<String>();
		Collections.addAll(idList,ids.split(","));
        channelSetService.batchDelChannelSet(idList);
        finOrderChannelService.batchDelFinOrderChannel(idList);
        return JsonResult.success();
    }

    public void initOrderChannel(CoreUser user,String channelCode){

        FinOrderChannel finOrder = new FinOrderChannel();
        finOrder.setTenantId(0);
        finOrder.setChannelCode("sdx");
        List<FinOrderChannel> finOrderChannels = finOrderChannelService.getSqlManager().template(finOrder);
        List<FinOrderChannel> list = new ArrayList<>();
        for (FinOrderChannel finOrderChannel : finOrderChannels) {
            FinOrderChannel channel = new FinOrderChannel();
            channel.setTenantId(user.getTenantId());
            channel.setChannelCode(channelCode);
            channel.setOrderType(finOrderChannel.getOrderType());
            channel.setOcStatus(1);
            channel.setPrice(finOrderChannel.getPrice());
            channel.setCreatedBy(user.getId().intValue());
            channel.setCreatedBy(user.getId().intValue());
            channel.setCreatedName(user.getName());
            channel.setCreatedTime(new Date());
            list.add(channel);
        }
        finOrderChannelService.getSqlManager().insertBatch(FinOrderChannel.class,list);
    }
    

}
